package com.lej.core.widget.customview

import android.content.Context
import android.os.CountDownTimer
import android.util.AttributeSet
import android.view.View
import com.lej.core.utils.ToastUtils

class TimerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : androidx.appcompat.widget.AppCompatTextView(context, attrs, defStyleAttr) {
    var endTime: Long = 0L
        set(value) {
            if (value <= System.currentTimeMillis()) {
                text = "00:00:00"
                return
            }

            field = value
            timer = object : CountDownTimer(endTime - System.currentTimeMillis(), 1000L) {
                override fun onFinish() {
                    ToastUtils.show("倒计时结束")
                }

                override fun onTick(diff: Long) {
                    val dif = diff / 1000//转换成s
                    val days = dif / (60 * 60 * 24)
                    val hours = (dif - days * (60 * 60 * 24)) / (60 * 60)
                    val minutes = (dif - days * (60 * 60 * 24) - hours * (60 * 60)) / 60
                    val seconds = (dif - days * (60 * 60 * 24) - hours * (60 * 60) - minutes * 60)
                    text = "${hours.change()}:${minutes.change()}:${seconds.change()}"
                }
            }
            timer?.cancel()
            timer?.start()
        }

    fun Long.change() = if (this < 10) "0${this}" else "$this"

    private var timer: CountDownTimer? = null

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        start()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stop()
    }

    override fun onVisibilityChanged(changedView: View, visibility: Int) {
        super.onVisibilityChanged(changedView, visibility)
        if (visibility == VISIBLE) {
            start()
        } else {
            stop()
        }
    }

    private fun start() {
        timer?.start()
    }

    private fun stop() {
        timer?.cancel()
    }
}